import time
import logging
from threading import Lock

# 64位ID的划分
WORKER_ID_BITS = 5
DATACENTER_ID_BITS = 5
SEQUENCE_BITS = 12

# 最大取值计算
MAX_WORKER_ID = -1 ^ (-1 << WORKER_ID_BITS)  # 2**5-1 = 31
MAX_DATACENTER_ID = -1 ^ (-1 << DATACENTER_ID_BITS)  # 2**5-1 = 31
MAX_SEQUENCE = -1 ^ (-1 << SEQUENCE_BITS)  # 2**12-1 = 4095

# 移位偏移计算
WORKER_ID_SHIFT = SEQUENCE_BITS  # 12
DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS  # 17
TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS  # 22

# 开始时间截 (2024-01-01 00:00:00 UTC)
TWEPOCH = 1704067200000

logger = logging.getLogger('django')


class IdWorker(object):
    """
    用于生成IDs的雪花算法工具类
    """

    def __init__(self, datacenter_id, worker_id, sequence=0):
        """
        初始化
        :param datacenter_id: 数据中心ID
        :param worker_id: 工作机器ID
        :param sequence: 序列号
        """
        # 数据中心ID范围判断
        if datacenter_id > MAX_DATACENTER_ID or datacenter_id < 0:
            raise ValueError(f'datacenter_id值必须大于0并且小于{MAX_DATACENTER_ID}')

        # 工作机器ID范围判断
        if worker_id > MAX_WORKER_ID or worker_id < 0:
            raise ValueError(f'worker_id值必须大于0并且小于{MAX_WORKER_ID}')

        self.worker_id = worker_id
        self.datacenter_id = datacenter_id
        self.sequence = sequence

        self.last_timestamp = -1  # 上次计算的时间戳
        self._lock = Lock()

    def _gen_timestamp(self):
        """
        生成整数时间戳
        :return:当前时间戳
        """
        return int(time.time() * 1000)

    def get_id(self):
        """
        获取新ID
        :return: 新ID
        """
        with self._lock:
            timestamp = self._gen_timestamp()

            # 时钟回拨判断
            if timestamp < self.last_timestamp:
                logging.error(f'时钟回拨. 拒绝生成ID生成{self.last_timestamp - timestamp}毫秒')
                raise ValueError('时钟回拨，拒绝生成ID')

            if timestamp == self.last_timestamp:
                self.sequence = (self.sequence + 1) & MAX_SEQUENCE
                if self.sequence == 0:
                    # sequence用完，等待下一毫秒
                    timestamp = self._til_next_millis(self.last_timestamp)
            else:
                self.sequence = 0

            self.last_timestamp = timestamp

            new_id = ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | \
                     (self.datacenter_id << DATACENTER_ID_SHIFT) | \
                     (self.worker_id << WORKER_ID_SHIFT) | \
                     self.sequence
            return new_id

    def _til_next_millis(self, last_timestamp):
        """
        等到下一毫秒
        """
        timestamp = self._gen_timestamp()
        while timestamp <= last_timestamp:
            timestamp = self._gen_timestamp()
        return timestamp


# 创建一个默认的ID生成器实例
ID_WORKER = IdWorker(1, 1)


def generate_id():
    """
    生成新的ID
    :return: 新ID
    """
    return ID_WORKER.get_id()

id = generate_id()
print(id)